import { _decorator, Component, Sprite } from 'cc';
const { ccclass, property } = _decorator;

@ccclass('AnimComponent')
export class AnimComponent extends Component {

    @property(Number)
    public interval: number = 0.02;
    @property(Number)
    public minIndex: number = 0;
    @property(Number)
    public maxIndex: number = 3;
    @property(String)
    public imageName: string = "";
    @property(Boolean)
    private isCompletion: boolean = false;
    @property(Boolean)
    public bLoop: boolean = true;

    private animSprite: Sprite;
    private curIndex: number = 0;
    private curTime: number = 0;
    public bPlayAnim: boolean = true;
    private spriteAtlas: any;

    onLoad() {
        this.animSprite = this.node.getComponent(Sprite);
        this.spriteAtlas = this.animSprite.getComponent(Sprite).spriteAtlas;
    }

    public ResetSprite() {
        this.animSprite.enabled = false;
    }

    public UpdatePlayAnimState(active) {
        this.bPlayAnim = active;
    }

    public Init(rootPath, max, name) {
        this.maxIndex = max;
        this.imageName = name;
        this.animSprite.getComponent(Sprite).spriteFrame = this.spriteAtlas.getSpriteFrame(this.imageName + this.curIndex);
        this.animSprite.enabled = true;
    }

    update(deltaTime: number) {
        if (this.bPlayAnim) {
            this.curTime = this.curTime + deltaTime;
            if (this.curTime - this.interval >= 0) {
                this.curIndex = this.curIndex + 1;
                this.UpdateFrame();
                this.curTime = 0;
            }
        }
    }

    public Reset(curValue) {
        this.curIndex = curValue;
        this.curTime = 0;
    }

    public SetSprite(index) {
        this.curIndex = index;
        let anmName = this.imageName + this.curIndex;
        if (this.isCompletion) {
            if (this.curIndex >= 10) {
                anmName = this.imageName + this.curIndex;
            }
            else {
                anmName = this.imageName + "0" + this.curIndex;
            }
        }
        this.animSprite.getComponent(Sprite).spriteFrame = this.spriteAtlas.getSpriteFrame(anmName);
    }

    UpdateFrame() {
        if (this.curIndex > this.maxIndex) {
            this.curIndex = this.minIndex;
            if (!this.bLoop) {
                this.bPlayAnim = false;
                return;
            }
        }
        this.SetSprite(this.curIndex);
        // GameAPI.LoadRoleImage(this.frameRootPath + "/" + this.imageName + this.curIndex + "/spriteFrame", this.animSprite);
    }

}


